const axios = require("axios");
const WxConfig = require("$config/wx.config");
const WXConfig = require("../../../config/wx.config");


/**
 * 微信
 */
class WxApiService {
	// 所有请求地址
	URL = {
		// 获取token
        getAccessToken: "https://api.weixin.qq.com/cgi-bin/token?grant_type=${0}&appid=${1}&secret=${2}",
        // 获取小程序码
        getWxACode: 'https://api.weixin.qq.com/wxa/getwxacode?access_token=${0}'
	};

	/**
	 * 获取token
	 */
	async getAccessToken() {
		try {
            const result = await axios.get(this._url('getAccessToken', ['client_credential', WxConfig.APPID, WXConfig.SECRET]));
            if (result.status === 200 && result.data && result.data.access_token) {
                return result.data;
            }
            return null;
		} catch (error) {
			console.log("微信Api获取AccessToken失败", error);
			return null;
		}
	}

    /**
     * 获取微信二维码
     * @param {string} path 跳转路径
     * @param {object} query 跳转页面的query参数
     */
    async getWxACode({ path, query } = {}) {
        const token = await this.getAccessToken(); // 获取token
        if (token && token.access_token) {
            try {
                path = path || 'pages/index/index'
                const qs = query ? this._qs(query) : null;
                const url = this._url('getWxACode', [token.access_token]);
                const reqPath = `${path}${(qs ? '?' + qs : '')}`; // 目标页面路径
                const data = {
                    path: reqPath, // 目标页面路径
                    width: 430, // 二维码宽度
                };
                const response = await axios.post(url, data, {
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    responseType: 'arraybuffer'
                })
                if (response.status === 200 && response.data && !response.data.errcode) {                    const base64String = Buffer.from(response.data).toString('base64');
                    return response.data
                }
                console.error('生成小程序码失败：', response.data.errmsg);
                return null;
            } catch (error) {
                console.error('生成小程序码失败：', error.response.data);
                return null;
            }
        }
    }

    // 转为qs
    _qs(data) {
        const qs = Object.keys(data).map(k => `${k}=${encodeURIComponent(data[k])}`).join('&')
        return qs;
    }

    /**
     * 路径序列化
     * @param {*} key 
     * @param {*} data 
     * @returns 
     */
    _url(key, data) {
        const url = this.URL[key];
        return url.replace(/\$\{(\w+)\}/g, (match, p1) => data[p1] || '');
    }
}

module.exports = new WxApiService();
